<template>
    <div class="materialContent">
        <div v-if="sceneValue === 'friend'">
            <transition-group class="material-content-friend" tag="div" @dragover="onDragoverImg($event)">
                <div
                    v-for="(item, index) in selectMaterials"
                    :key="item.id"
                    :draggable="!props.disabled"
                    @dragstart="onDragStartImg(item, index)"
                    @dragenter="onDragEnterImg(index, $event)"
                    @dragend="onDragEndImg()"
                    @dragover="onDragoverImg($event)">
                    <div class="friend-item">
                        <el-icon v-if="!props.disabled" class="friend-item-del" @click="onDel(index)">
                            <CircleCloseFilled />
                        </el-icon>
                        <template v-if="item.type == 1">
                            <el-image
                                class="friend-img"
                                :src="item.thumbnail_url || item.url"
                                :initial-index="previewIndex"
                                :preview-src-list="previewImgList"
                                lazy
                                fit="cover"
                                @click="onPreviewImgList(index)"></el-image>
                        </template>
                        <template v-if="item.type == 2">
                            <div @click="openMaterialLib(materialTabs[1])">
                                <img
                                    class="video-play-icon"
                                    src="//img.static-keyid.cn/toolspace/scrm/2023/09/16951997873589jywsq9syknh3d8e.png" />
                                <el-image
                                    class="friend-img"
                                    :src="
                                        item.thumbnail_url ||
                                        `${item.url}?x-oss-process=video/snapshot,t_0,f_jpg,w_320,h_240,m_fast`
                                    "
                                    lazy
                                    fit="cover"></el-image>
                            </div>
                        </template>
                        <template v-if="item.type == 3">
                            <div class="friend-link-box" @click="openMaterialLib(materialTabs[2])">
                                <el-image
                                    class="link-img"
                                    :src="item.cover_image_url || item.url"
                                    fit="cover"></el-image>
                                <div class="link-right">
                                    <div
                                        class="link-name"
                                        :class="{ 'link-name-overflow': item.desc || item.link_desc }">
                                        {{ item.name }}
                                    </div>
                                    <div class="link-desc">{{ item.desc || item.link_desc }}</div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </transition-group>
        </div>
        <div v-else class="material-content-list">
            <div v-for="(item, index) in selectMaterials" :key="item.id || item.name" class="material-item">
                <div class="content">
                    <img :src="item.icon" alt="" />
                    <span>{{ item.name }}</span>
                </div>
                <el-icon v-if="!props.disabled && !(item.is_default_del === 1)" @click="onDel(index)">
                    <CircleCloseFilled />
                </el-icon>
            </div>
        </div>
        <div class="material-content-com">
            <el-popover
                v-if="materialTabs.length"
                popper-class="pop_select_box"
                :placement="placement"
                trigger="hover"
                :width="popoverWidth"
                :disabled="props.materialDisabled || props.disabled || sceneDisabled">
                <template #reference>
                    <div
                        v-if="isTabsFriend"
                        class="upload_btn"
                        :class="{ disabled: props.disabled || props.materialDisabled }">
                        <el-icon><plus /></el-icon>
                        <span v-if="sceneDisabled" class="upload_text" @click="openMaterialLib(materialTabs[0])">
                            上传图片
                        </span>
                        <span v-else class="upload_text">{{ materialLabels }}</span>
                    </div>
                </template>
                <template #default>
                    <div v-if="selectMaterials.length < props.maxNum" class="upload_pop">
                        <div v-for="tab in materialTabs" :key="tab.type" class="item_pop" @click="openMaterialLib(tab)">
                            <img class="item_pop_icon" :src="tab.icon" alt="" />
                            <span class="item_pop_name">{{ tab.name }}</span>
                        </div>
                    </div>
                    <div v-else class="upload_default_pop">
                        <span>已达添加上限{{ props.maxNum }}个</span>
                    </div>
                </template>
            </el-popover>
        </div>
    </div>
    <ZwMaterialLib
        ref="ZWMaterialLibRef"
        v-model="materialLibShow"
        :show-tabs-list="showTabsList"
        :max-num="props.maxNum"
        :disabled="props.disabled"
        :scene-value="props.sceneValue"
        @submit="getMaterialLib" />
</template>
<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted, nextTick, withDefaults } from 'vue';
import { getHashTabs, typeConvert } from '../utils/material';
import ZwMaterialLib from '../../ZwUnityKitMaterialLib/index.vue';

interface Props {
    /** 素材展示tabs内容 */
    tabs?: Array<any>;
    /** 素材最大数量 */
    maxNum?: number;
    /** 素材选择内容回显使用 */
    materialData?: Array<any>;
    /** 素材是否禁用 */
    materialDisabled?: boolean;
    /** 整个素材是否禁用 */
    disabled?: boolean;
    /** 场景值 */
    sceneValue?: string;
}

const props = withDefaults(defineProps<Props>(), {
    tabs: () => [1, 2, 3, 4, 5, 6, 7, 9, 10, 11],
    maxNum: 9,
    materialData: () => [],
    materialDisabled: false,
    disabled: false,
    sceneValue: ''
});

const emit = defineEmits(['change']);

const placement = computed(() => {
    return selectMaterials.value.length < props.maxNum ? 'bottom-start' : 'top';
});

const popoverWidth = computed(() => {
    const labelWidth = 36 + props.tabs.length * 44 + (props.tabs.length - 1) * 8;
    return selectMaterials.value.length < props.maxNum ? labelWidth : 150;
});

/** tabs文案展示 */
const materialLabels = computed(() => {
    const str = '';
    return props.tabs.reduce((pre, tabKey, index, arr) => {
        return `${pre}${hashTabs.value[tabKey].name}${index < arr.length - 1 ? '/' : ''}`;
    }, str);
});

/** 展示素材tabs，有name，icon等内容 */
const materialTabs = computed(() => {
    return props.tabs.map(tabKey => {
        return hashTabs.value[tabKey];
    });
});

/**
 * 素材弹框tabs展示
 * 在朋友圈场景下指定类型1-图片，2-视频，3-链接
 */
const showTabsList = computed(() => {
    return props.sceneValue == 'friend' ? [1, 2, 3] : props.tabs;
});

/** 朋友圈场景-选中图片预览列表 */
const previewImgList = computed(() => {
    const list: any = [];
    selectMaterials.value.map((el: any) => {
        if (el.type == 1) {
            list.push(el.thumbnail_url || el.url);
        }
    });
    return list;
});

/**
 * 朋友圈场景下素材tabs的tooltip是否禁用
 */
const sceneDisabled = computed(() => {
    return props.sceneValue == 'friend' && selectMaterials.value.length;
});

/**
 * 朋友圈场景下选择视频与图片不展示tabs
 */
const isTabsFriend = computed(() => {
    return !(props.sceneValue == 'friend' && selectMaterials.value.length && selectMaterials.value[0]?.type != 1);
});

/** 素材弹框 ref */
const ZWMaterialLibRef = ref<any>();

/** 素材弹框是否展示 */
const materialLibShow = ref(false);

/**  */
const hashTabs = ref<any>(getHashTabs());

/**
 * 选中素材list
 * 包括素材与本地上传，本地上传数据有local: true字段
 */
const selectMaterials = ref<Array<any>>([]);

// const welcomeFriendId = ref(""); // 已有欢迎语id

/** 朋友圈场景-选中图片预览列表下标 */
const previewIndex = ref(0);

/**
 * 朋友圈场景-图片拖拽信息
 */
const imgDragInfo = reactive({
    oldIndex: 0,
    oldInfo: {},
    newIndex: 0
});

/**
 * 打开素材弹框
 * 设置回显selectInfo数据
 * @param tab
 */
const openMaterialLib = tab => {
    if (props.disabled || props.materialDisabled) return;
    ZWMaterialLibRef.value.tabsType = tab.type;
    const list = selectMaterials.value.filter((el: any) => !el.local);
    const ary = selectMaterials.value.filter((el: any) => el.local);
    ZWMaterialLibRef.value.selectInfo.materialList = list;
    ZWMaterialLibRef.value.selectInfo.localMaterialList = ary;

    materialLibShow.value = true;
};

/**
 * 删除某一项选中素材
 * @param index 下标第几项
 */
const onDel = index => {
    if (props.disabled) return;
    selectMaterials.value.splice(index, 1);
    onUpdateMaterials();
};

/**
 * 获取素材弹框选择数据
 * @param res 选择素材数据
 * @param localList 本体上传数据
 */
const getMaterialLib = (res = [], localList = []) => {
    selectMaterials.value = [];
    const list: any = [];
    const ary = [];
    res.map((item: any) => {
        item.selectList.map(el => {
            list.push({ ...formatMaterials(item.type, el) });
        });
    });

    localList.map((item: any) => {
        list.push({ ...formatLocalMaterials(item.type, item) });
    });

    selectMaterials.value.push(...list);

    const sortList = selectMaterials.value.filter(el => el.sort).sort((a, b) => a.sort - b.sort);
    const sortTimeList = selectMaterials.value
        .filter(el => el.sortTime && !el.sort)
        .sort((a, b) => a.sortTime - b.sortTime);
    selectMaterials.value = [...sortList, ...sortTimeList];

    selectMaterials.value = filterOfficialAccountsData(selectMaterials.value);

    selectMaterials.value.splice(props.maxNum);
    onUpdateMaterials();
};

/**
 * 格式化选中素材数据
 * @param type 类型
 * @param val
 */
const formatMaterials = (type, val) => {
    const { id, title, file_name, is_radar, sortTime, desc } = val;
    let name = file_name || title || val.link_title || val.name;
    const icon = hashTabs.value[type]?.icon;
    const defaultData = {};
    switch (type) {
        case 0:
            break;
        case 6:
            name = val.activity_name;
            break;
        case 7:
            name = val.product_name || val.page_name;
            break;
        case 10:
            return mapOfficialAccountsData(val) || val;
    }
    if (val.is_default_del === 1) {
        defaultData['is_default_del'] = val.is_default_del;
        defaultData['linkUrl'] = val.linkUrl;
        defaultData['link_decs'] = val.link_decs;
        defaultData['link_share_image'] = val.link_share_image;
        defaultData['link_title'] = val.link_title;
    }
    return {
        ...val,
        type,
        id,
        title,
        is_radar,
        sortTime,
        name,
        icon
    };
};

/**
 * 本地素材处理
 * @param type
 * @param val
 */
const formatLocalMaterials = (type, val) => {
    const { id, title, file_name, is_radar, sortTime, desc } = val;
    const name = file_name || title || val.name;
    const icon = hashTabs.value[type]?.icon;
    const defaultData = {};
    return {
        ...val,
        type,
        id,
        title,
        is_radar,
        sortTime,
        name,
        icon
    };
};

/**
 * 公众号素材处理
 * @param arr
 */
const filterOfficialAccountsData = arr => {
    const list: any = [];
    arr?.map(item => {
        if (item.type == 10) {
            if (item?.list) {
                item?.list.map(i => {
                    list.push(i);
                });
            } else {
                list.push(item);
            }
        } else {
            list.push(item);
        }
    });
    return list;
};

/**
 * 公众号素材处理
 * @param param0
 */
const mapOfficialAccountsData = ({ article_detail }: any = []) => {
    const list = [
        {
            name: '',
            type: 1,
            iconUrl: 'https://img.static-keyid.cn/toolspace/scrm/2023/09/1694768748465id8echwhbttfxakt.png'
        },
        {
            name: '',
            type: 2,
            iconUrl: 'https://img.static-keyid.cn/toolspace/scrm/2023/09/1694670511980clgmgxz8ixla8v9n.png'
        },
        {
            name: '视频',
            type: 3,
            iconUrl: 'https://img.static-keyid.cn/toolspace/scrm/2023/08/16928475688217hve14b7fwni5y3j.png'
        },
        {
            name: '音频',
            type: 4,
            iconUrl: 'https://img.static-keyid.cn/toolspace/scrm/2023/08/1692844697283st4m7jbhe5ubc8wj.png'
        },
        {
            name: '图片',
            type: 5,
            iconUrl: 'https://img.static-keyid.cn/toolspace/scrm/2023/09/1694670496752ytir0j1cdpff4wym.png'
        }
    ];
    if (article_detail?.length) {
        const arr = article_detail.slice(0, props.maxNum).map(item => {
            const type = 10;
            const { type: articleType, id } = item;
            const info: any = list.find(el => el.type == articleType) || {};
            const name = info?.name || item.title;
            let icon = '';
            if (articleType === 1) {
                icon = item.cover;
            } else {
                icon = info?.iconUrl || '';
            }
            return { type, id, articleType, name, icon };
        });
        return { type: 10, list: arr };
    } else {
        return null;
    }
};

/**
 * 更新素材选中数据给父级
 * 朋友圈场景数据格式特殊处理
 * @param content
 */
const onUpdateMaterials = () => {
    selectMaterials.value.map((el, index) => {
        el.sort = index + 1;
    });
    if (props.sceneValue === 'friend') {
        const list: any = [];
        selectMaterials.value.map(el => {
            const info: any = typeConvert(el.type, el.local, 'typeToName');

            info.type = info.typeName;
            if (!el.local) {
                info[info.typeName].content_id = el.id;
            } else {
                info[info.typeName].code = el.code;
                info[info.typeName].url = el.url;
            }
            if (el.type == 3) {
                info[info.typeName].link_title = el.name;
                info[info.typeName].link_url = el.link_url || el.absolute_url;
                info[info.typeName].link_image_url = el.cover_image_url;
                info[info.typeName].link_desc = el.desc || el.link_desc;
            }
            if (el.editId) {
                info[info.typeName].id = el.editId;
            }
            const item = {
                ...info,
                sort: el.sort
            };
            delete item.local;
            delete item.typeName;
            delete item.editId;
            list.push(item);
        });

        emit('change', list);
    } else {
        emit('change', selectMaterials.value);
    }
};

const clearMaterial = () => {};

const initMaterial = () => {};

const getPropsMaterlis = () => {
    const list = [];
    if (props.sceneValue === 'friend') {
        selectMaterials.value;
        props.materialData?.map(el => {
            const info: any = typeConvert(el.type, false, 'nameToType');
            const item: any = {};
            if (info.local) {
                item.local = true;
            }
            if (info.type == 3) {
                item.name = el[el.type]?.link_title;
                item.link_url = el[el.type]?.link_url;
                item.link_desc = el[el.type]?.link_desc;
                item.cover_image_url = el[el.type]?.link_image_url;
            }
            if (el[el.type]?.code) {
                item.code = el[el.type]?.code;
            }
            item.type = info.type;
            item.url = el[el.type]?.url;
            item.id = el[el.type]?.content_id;
            item.editId = el[el.type]?.id;
            item.sort = el.sort;
            selectMaterials.value.push(item);
        });
    } else {
        props.materialData?.map(el => {
            const info = el;
            info.id = el?.content_id;
            const { id, title, file_name, is_radar, sortTime, desc } = info;
            let name = file_name || title || info.name;
            const icon = hashTabs.value[info.type]?.icon;
            switch (info.type) {
                case 0:
                    break;
                case 3:
                    name = info.link_title;
                    break;
                case 6:
                    name = info.link_title;
                    break;
                case 7:
                    name = info.link_title;
                    break;
                case 10:
                    name = info.link_title;
                    break;
            }
            selectMaterials.value.push({
                ...info,
                id,
                title,
                is_radar,
                sortTime,
                name,
                icon
            });
        });
    }
    onUpdateMaterials();
};

const onPreviewImgList = index => {
    previewIndex.value = index;
};

const onDragoverImg = e => {
    e.preventDefault();
};

/**
 * 图片拖拽排序处理
 * @param val 当前值
 * @param index 当前下标
 */
const onDragStartImg = (val, index) => {
    imgDragInfo.oldInfo = val;
    imgDragInfo.oldIndex = index;
};

/**
 * 图片拖拽排序处理
 * @param val
 * @param index
 * @param e
 */
const onDragEnterImg = (index, e) => {
    imgDragInfo.newIndex = index;
    onDragoverImg(e);
};

const onDragEndImg = () => {
    if (props.disabled) return;
    selectMaterials.value.splice(imgDragInfo.oldIndex, 1);
    selectMaterials.value.splice(imgDragInfo.newIndex, 0, imgDragInfo.oldInfo);
    selectMaterials.value.map((el, index) => {
        el.sort = index + 1;
    });
    onUpdateMaterials();
};

watch(
    () => props.materialData,
    val => {
        nextTick(() => {
            getPropsMaterlis();
        });
    },
    { immediate: true, deep: true }
);

onMounted(() => {});

defineExpose({
    clearMaterial
});
</script>

<style lang="scss" scoped src="./MaterialComponent.scss"></style>
